package com.br.aiops.rule;

import com.br.aiops.rule.db.RuleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 规则缓存类
 */
@Component
public class RuleCache {

    private static final Logger LOGGER = LoggerFactory.getLogger(RuleCache.class);

    @Autowired
    private RuleService ruleService;

    private List<Rule> rules;

    /**
     * 获取所有规则
     * 如果rules为空，则执行load方法加载
     * @return 规则列表
     */
    public List<Rule> getRules() {
        if (rules == null) {
            load();
        }
        return new ArrayList<>(rules);
    }

    public synchronized void load() {
        rules = ruleService.getRules();
    }

    @Scheduled(fixedDelay = 60 * 1000)
    private void refresh() {
        load();
        LOGGER.debug("刷新Rules完成，刷新后的rules为：{}。", rules);
    }
}
